#include <cmath>
#include <csignal>
#include <cstring>
#include <iostream>
#include <sstream>
#include <unistd.h>

#include <ipc_server.h>

void SignalHandler(int signum)
{
    std::cerr << "stopping by signal " << signum << std::endl;
    IpcServer::GetInstance()->Stop();
}

class SqrtCalcService : public IIpcService {
public:
    virtual int GetID() const override
    {
        return 123;
    }

    virtual void Process(IpcMessageParcel &parcel) override
    {
        auto reply = parcel;
        reply.way = IpcMessageParcel::Way::syncback;

        int id = 0;
        const char *command = "get ";
        if (parcel.data.find(command) == 0) {
            std::stringstream ss;
            ss << parcel.data.substr(strlen(command));
            ss >> id;
            if (!ss.eof() || !ss) {
                reply.data = "invalid number";
                IpcServer::GetInstance()->Send(reply, reply);
                return;
            }
        } else {
            reply.data = "invalid command";
            IpcServer::GetInstance()->Send(reply, reply);
            return;
        }

        std::stringstream ss;
        ss << (int)sqrt(id);
        reply.data = ss.str();
        IpcServer::GetInstance()->Send(reply, reply);
        return;
    }
};

int main()
{
    std::signal(SIGINT, SignalHandler);

    IpcServiceRegistry registry;
    SqrtCalcService service;
    registry.AddService(service);

    auto server = IpcServer::GetInstance();
    server->SetRegistry(registry);
    auto ret = server->Start(55555);
    if (ret) {
        return ret;
    }

    server->Run();
    return 0;
}
